package com.hongshan.wallet.core.trading

import android.app.Application
import android.databinding.ObservableField
import com.hongshan.wallet.Constant
import com.hongshan.wallet.base.MyViewModel
import com.hongshan.wallet.base.SingleLiveEvent
import com.hongshan.wallet.http.HttpClient
import com.hongshan.wallet.tryRun
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

/**
 * Copyright Zhangxx.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.core.trading
 * @author   : zhangxx
 * @date     : 2019/3/22
 * @email    : qq957413212@hotmail.com
 */
class TradingPagerViewModel(application: Application, val pageIndex: Int) : MyViewModel(application) {

    val title = arrayOf("待收款", "已完成", "已失效")[pageIndex]

    val status = arrayOf(0, 1, 2)[pageIndex]

    val recycleAdapter = TradingRecycleAdapter(arrayListOf())

    val refreshComplete = SingleLiveEvent<Boolean>()

    var startTime: Long? = null

    var endTime: Long? = null

    val refreshEnable = ObservableField(true)
    val loadMoreEnable = ObservableField(true)

    val onRefresh = OnRefreshListener {
        refresh(startTime, endTime, 1,it)
    }

    val onLoad = OnLoadMoreListener {
        refresh(startTime, endTime, recycleAdapter.list.size / Constant.OTHER_CONFIG.ROWS + 1,it)
    }

    fun refresh(startTime: Long?, endTime: Long?, page: Int, refreshLayout: RefreshLayout? = null) {
        this.startTime = startTime
        this.endTime = endTime
        GlobalScope.launch(Dispatchers.Main) {
            val result = GlobalScope.async(Dispatchers.IO) {
                tryRun {
                    HttpClient.httpApi.getOrderList(page, Constant.OTHER_CONFIG.ROWS, status, startTime, endTime)
                        .execute()
                }
            }
            val body = result.await()?.body()
            refreshLayout?.finishLoadMore()
            refreshLayout?.finishRefresh()
            refreshComplete.value = !(page ==1 && body?.data?.list?.size?:0 <= 0)
            if (body?.code == 0) {
                if (page == 1) {
                    recycleAdapter.list.clear()
                }
                loadMoreEnable.set(body.data.list.size >= Constant.OTHER_CONFIG.ROWS)
                recycleAdapter.list.addAll(body.data.list)
                recycleAdapter.notifyDataSetChanged()
            }
        }
    }

    override fun initial() {
        super.initial()
        if (pageIndex == 0){
            recycleAdapter.refreshListener = { refresh(startTime, endTime, 1, null) }
        }
    }
}
// android-apt plugin is incompatible with the Android Gradle plugin.  Please use 'annotationProcessor' configuration instead.